import wx from "weixin-js-sdk";
import Vue from "vue";
import { Geting } from "@/utils/axios";
import ajax from "@/utils/ajax";
import { getQueryString } from "@/utils/utils";

Geting(`/usermanager/h5/houseSources/ticket`, {
    projectId: getQueryString('projectId'),
    tenantId: getQueryString('tenantId'),
    url: location.href
}).then(function(res) {
        if (!res.isSuccess) {
            console.log("获取微信签名信息错误");
            return;
        }
        let data = res.data;
        console.log(data);
        wx.config({
            debug: false, // 开启调试模式,
            appId: data.appId, // 必填，企业号的唯一标识，此处填写企业号corpid
            timestamp: data.timestamp, // 必填，生成签名的时间戳
            nonceStr: data.nonceStr, // 必填，生成签名的随机串
            signature: data.signature, // 必填，签名，见附录1
            jsApiList: [
                "getLocation",
                "openLocation"
            ] // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
        });
        wx.ready(() => {
            console.log("wx 成功");
            // wx.getLocation({
            //   type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
            //   success: (res) => {
            //     cityName(res.latitude,res.longitude);
            //   }
            // });
        });
        wx.error(function(res) {
            console.log("err", res);
        });
    }
);
//将经纬度转换成城市名和街道地址，参见百度地图接口文档：http://developer.baidu.com/map/index.php?title=webapi/guide/webservice-geocoding
function cityName(latitude, longitude){
  ajax({
    jsonp:'renderReverse',
    url: 'http://api.map.baidu.com/geocoder/v2/?ak=j2sy6K7okugeW8CR00ACyKYXGnRWQGHL&callback=renderReverse&location=' + latitude + ',' + longitude + '&output=json&pois=1',
    data:{},
    time:1000,
    success:function(data){
      localStorage.setItem("mapCityName",data.result.addressComponent.city);   // 百度根据经纬度获取城市名
    },
    error:function(error){
     console.log(error)
    }
   })
}
export function getLocation() {
    // 获取用户地理位置，微信公众号的jdk
    wx.getLocation({
      type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
      success: (res) => {
        cityName(res.latitude,res.longitude);
      }
    });
}
export function chooseImage() {
    return new Promise((resolve, reject) => {
        wx.chooseImage({
            count: 1, // 默认9
            sizeType: ["compressed"], // 可以指定是原图还是压缩图，默认二者都有
            sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
            success: function(res) {
                for (let i = 0; i < res.localIds.length; i++) {
                    wx.uploadImage({
                        localId: res.localIds[i], // 需要上传的图片的本地ID，由chooseImage接口获得
                        isShowProgressTips: 1, // 默认为1，显示进度提示
                        success: function(res) {
                            console.log("拍照:----");
                            console.log(res);
                            var serverId = res.serverId; // 返回图片的服务器端ID
                            uploadFile(resolve, reject, serverId, ".jpg");
                        }
                    });
                }
            }
        });
    });
}
function uploadFile(resolve, reject, serverId, ext, time, cb) {
    console.log(time);
    Geting("/customerserviceownerh5/h5/colorlife/wxFile", {
        media_id: serverId,
        fileName: new Date().getTime() + ext
    }).then(result => {
        if (result.isSuccess) {
            console.log(result, ext);
            if (ext === ".amr") {
                resolve({
                    accessUrl: result.data.accessUrl,
                    duration: time
                });
                cb(
                    {
                        accessUrl: result.data.accessUrl,
                        duration: time
                    },
                    { data: result }
                );
            } else {
                resolve(result.data.accessUrl);
            }
        } else {
            reject(new Error("上传文件失败"));
        }
    });
}
var template = `
  <div style="width:100%;height:20%;"></div>
  <div class="rprogress"><div class="rschedule"></div></div>
  <br/>
  <div id="rtime" class="rtime">00:00:00</div><br/>
  <div class="stop" onclick="stopRecord()"></div>
`;
let node = document.createElement("div");
node.id = "record";
node.className = "rp";
node.innerHTML = template;
let rt = null;
// let r = null;
let ri = null;
let t = 0;
let duration = 0;
export function audioRecord(cb) {
    return new Promise((resolve, reject) => {
        startRecord();
        stop(resolve, reject, cb);
    });
}
function startRecord() {
    document.body.appendChild(node);
    console.log("开始录音：");
    rt = document.getElementById("rtime");
    wx.startRecord();
    node.style.display = "block";
    t = 0;
    ri = setInterval(function() {
        t++;
        rt.innerText = timeToStr(t);
    }, 1000);
}
function timeToStr(ts) {
    if (isNaN(ts)) {
        return "--:--:--";
    }
    var h = parseInt(ts / 3600);
    var m = parseInt((ts % 3600) / 60);
    var s = parseInt(ts % 60);
    return ultZeroize(h) + ":" + ultZeroize(m) + ":" + ultZeroize(s);
}
console.log(duration);
function stop(resolve, reject, cb) {
    duration = 0;
    // 停止录音
    window.stopRecord = function() {
        node.style.display = "none";
        rt.innerText = "00:00:00";
        clearInterval(ri);
        ri = null;
        duration = t;
        if (t < 3) {
            Vue.toast("录音时间不能少于3秒");
            return;
        } else if (t > 60) {
            Vue.toast("录音时间不能超过1分钟");
            return;
        }
        wx.stopRecord({
            success: function(res) {
                var localId = res.localId;
                wx.uploadVoice({
                    localId: localId, // 需要上传的音频的本地ID，由stopRecord接口获得
                    isShowProgressTips: 1, // 默认为1，显示进度提示
                    success: function(res) {
                        console.log("录音:----");
                        console.log(res);
                        var serverId = res.serverId; // 返回音频的服务器端ID
                        uploadFile(
                            resolve,
                            reject,
                            serverId,
                            ".amr",
                            duration,
                            cb
                        );
                    }
                });
            }
        });
        // w = null
        t = 0;
    };
}
function ultZeroize(v, l) {
    let z = "";
    l = l || 2;
    v = String(v);
    for (let i = 0; i < l - v.length; i++) {
        z += "0";
    }
    return z + v;
}
